package Midium;

import java.util.List;

//24.两两交换链表中的节点
public class Solution24 {
    public static ListNode swapPairs(ListNode head) {
        if(head==null||head.next==null)
            return head;
        if(head.next.next==null){
            head.next.next=head;
            ListNode p = head.next;
            head.next=null;
            return p;
        }
        ListNode p=null,q=null,r=null,pre=null,res=null;
        boolean first = true;
        p=head;
        q=p.next;
        r=q.next;
        while (q!=null){
            q.next=p;
            p.next=r;
            if(pre!=null)
                pre.next=q;
            try {
                r = r.next;
            }catch (NullPointerException e){
                r=null;
            }
            pre=q;
            if(first){
                res =pre;
                first=false;
            }
            q=p.next;
            try {
                r = r.next;
            }catch (NullPointerException e){
                r=null;
            }
            try {
                q = q.next;
            }catch (NullPointerException e){
                q=null;
            }
            p=p.next;
            pre=pre.next;
        }
        return res;
    }

    public static void main(String[] args) {
        swapPairs(new ListNode(1,new ListNode(2, new ListNode(3,new ListNode(4)))));
    }
}
